<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="地址" prop="adress">
        <el-input v-model="queryParams.adress" placeholder="请输入名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 页面功能操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:application:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:application:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:application:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:application:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- table表格 -->
    <el-table v-loading="loading" :data="townList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="图片" align="center" prop="preViewImg" width="300">
        <template slot-scope="scope">
          <el-image v-for="(item, index) in scope.row.imagesUrl" :key="index" :src="baseurl + item"
            style="width:50px;height:50px;" :preview-src-list="scope.row.previewImg">
          </el-image>
        </template>
      </el-table-column>
      <!-- <el-table-column label="乡镇介绍" align="center" prop="context">
        <template slot-scope="scope">
          <div :title="scope.row.context" v-html="scope.row.context" style="height:100px;overflow:hidden"></div>
        </template>
      </el-table-column> -->
      <el-table-column label="地址" align="center" prop="adress" />
      <el-table-column label="创建人" align="center" prop="adminUser" />
      <el-table-column label="操作" align="center" fixed="right" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:application:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:application:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改模块对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" append-to-body
      @close="dioClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="所属省市" prop="pcc">
          <el-cascader v-model="form.pcc" :options="proceCityList" clearable filterable style="width: 100%;"></el-cascader>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <imageUpload v-model="form.image" @uploadImage="uploadimg" @remove="removeImg" :limit="9" />
        </el-form-item>
        <el-form-item label="介绍" prop="context">
          <!-- <el-input type="textarea" v-model="form.context" placeholder="请输入" :autosize="{ minRows: 5, maxRows: 30}" /> -->
          <editor v-if="open" v-model="form.context" :min-height="192" />
        </el-form-item>
        <el-form-item label="地址" prop="adress">
          <zxMap :value="latLng" :address="form.adress" @input="mapClick" v-if="open"></zxMap>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" disabled />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { townShip_list, townShip_add, townShip_update, townShip_delete, townShip_info } from "@/api/application/application/application";
import ImageUpload from "@/components/UploadImage";
import zxMap from "@/components/map/index";
import Editor from "@/components/Editor";
import { addresLevel_two } from "@/utils/tool"
import axios from 'axios'
export default {
  name: "Application",
  components: {
    ImageUpload,
    zxMap,
    Editor
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      productImgs: [],
      isMultiple: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 乡镇表格数据
      townList: [],
      //乡镇管理员列表
      townAdminList: [],
      fileUploadList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        title: null,
        adress: null,
        adminUser: null,
        userName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        pcc: [{ required: true, message: '请输入', trigger: 'blur' }],
        title: [{ required: true, message: '请输入', trigger: 'blur' }],
        image: [{ required: true, message: '请选择', trigger: 'blur' }],
        context: [{ required: true, message: '请输入', trigger: 'blur' }],
        adress: [{ required: true, message: '请选择', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择', trigger: 'blur' }],
        longitude: [{ required: true, message: '请在上方地图获取经纬度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请在上方地图获取经纬度', trigger: 'blur' }],
      },
      latLng: "",
      proceCityList: [],//省市地区列表
    };
  },
  created() {
    this.getAddressJson();
    this.getList();

  },
  methods: {
    /** 获取json地址数据 */
    getAddressJson() {
      axios({
        method: "get",
        url: "https://restapi.amap.com/v3/config/district?parameters",
        params: {
          key: "6f7d5b0d72bd01c75ee27d4a99c66c8c",
          subdistrict: "4",
        },
        output: "JSON"
      }).then(res => {
        if (res.data.status === "1") {
          let { districts } = res.data.districts[0];
          districts.forEach(one => {
            //省份数据处理
            one.value = one.name;
            one.label = one.name;
            one.children = (one.districts.length === 0 && !one.districts) ? [] : one.districts;

            //市级数据处理
            one.children.forEach(two => {
              two.value = two.name;
              two.label = two.name;
              two.children = (two.districts.length === 0 && !two.districts) ? [] : two.districts;

              //区县级数据处理
              two.children.forEach(three => {
                three.value = three.name;
                three.label = three.name;
                three.children = (three.districts.length === 0 && !three.districts) ? [] : three.districts;


                //乡镇街道数据处理
                three.children.forEach(four => {
                  four.value = four.name;
                  four.label = four.name;
                });
              });
            });
          });
          this.proceCityList = districts;
        } else {
          this.msgError("获取行政区域数据失败");
        };
      })
    },
    /** 查询乡镇列表 */
    async getList() {
      this.loading = true;
      let res = await townShip_list(this.queryParams);
      let { code, rows, total } = res;
      if (code === 200) {
        rows.forEach((item) => {
          if(item.imageScale){
            let previewImg = [];
            item.imagesUrl = item.imageScale.split(",");
            item.imagesUrl.forEach((val) => {
              previewImg.push(this.baseurl + val);
              item.previewImg = previewImg;
            });
          }
        });
        this.townList = rows;
        this.total = total;
        this.loading = false;
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // location.reload();
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        title: null,
        image: null,
        context: null,
        adress: null,
        longitude: null,
        latitude: null,
        pcc: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加乡镇";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改乡镇";
      townShip_info({ id: row.id }).then(res => {
        res.data.userId = Number(res.data.userId);
        res.data.pcc = !res.data.pcc ? [] : res.data.pcc.split(",");
        this.latLng = res.data.longitude + "," + res.data.latitude;
        this.form = res.data;
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      //获取用户信息
      let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      this.$refs["form"].validate(async valid => {
        this.form.pcc = this.form.pcc.join(",");
        if (valid) {
          if (this.form.id != null) {
            let res = await townShip_update(this.form);
            let { code, msg } = res;
            if (code === 200) {
              this.msgSuccess(msg);
              this.open = false;
              this.getList();
            };
          } else {
            this.form.adminId = userInfo.userId;
            let res = await townShip_add(this.form);
            let { code, msg } = res;
            if (code === 200) {
              this.msgSuccess(msg);
              this.open = false;
              this.getList();
            };
          }
          // location.reload();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除乡镇名称为"' + row.name + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        let res = await townShip_delete(ids);
        if (res.code === 200) {
          this.getList();
          this.msgSuccess("删除成功");
        };
      }).catch(() => {
        this.msgInfo("取消删除");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有模块数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        // return exportApplication(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    //图片上传事件
    uploadimg(e) {
      this.form.image = e;
    },
    //删除图片事件
    removeImg(e) {
      this.form.image = e;
    },
    /* 地图事件 */
    mapClick(e) {
      console.log(e);
      let latlng = e.lnglat.split(",");
      this.form.longitude = latlng[0];
      this.form.latitude = latlng[1];
      this.form.adress = e.address;
    },
    /* dio关闭时触发 */
    dioClose() {
      this.latLng = "";
    },
  }
};
</script>
